package LeetCode;

import java.util.Arrays;

//
// Created by ✎﹏ℳ๓独赏☆独醉 on 2024/5/11.
//
//https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
public class 在排序数组中查找元素的第一个和最后一个位置 {
    public static void main(String[] args) {
        int[] nums = {2,2};
        int target = 1;
        System.out.println(Arrays.toString(searchRange(nums,target)));
    }

    public static int[] searchRange(int[] nums, int target) {
        int[] res = {-1,-1};
        if(nums.length == 0 || nums[0] > target || nums[nums.length - 1] < target)return res;
        if(nums.length == 1){
            if(nums[0] == target)return new int[]{0,0};
            else return res;
        }
        int left = 0,right = nums.length;
        while (left < right){
            int mid = (left + right) / 2;
            if(nums[mid] >= target)right = mid;
            else left = mid + 1;
        }
        if(nums[right] == target)res[0] = right;
        left = 0;right = nums.length;
        while(left < right){
            int mid = (left + right) / 2;
            if(nums[mid] <= target)left = mid + 1;
            else right = mid;
        }
        if(nums[left - 1] == target)res[1] = left - 1;
        return res;
    }
}
